package com.showboom.elauncher.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;

import com.showboom.elauncher.R;
import com.showboom.elauncher.util.Util;

public class NoNetActivity extends Activity implements View.OnClickListener{

    Button btnOpenSettings;
    NetListnerReceiver netListnerReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.no_net_activity);

        btnOpenSettings = findViewById(R.id.btn_open_settings);
        btnOpenSettings.setOnClickListener(this);
        initReceiver();
    }

    private void initReceiver() {
        netListnerReceiver = new NetListnerReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netListnerReceiver, filter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(Util.hasWifiConnection(this)) {
            finish();
        }
    }

    private class NetListnerReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = manager.getActiveNetworkInfo();
            if (networkInfo != null) {
                if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                    NoNetActivity.this.finish();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(netListnerReceiver);
    }

    @Override
    public void onClick(View v) {
        if(btnOpenSettings == v) {
            Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
            startActivity(intent);
        }
    }
}
